package com.xiaotu.service.Impl;

import com.xiaotu.pojo.Comment;
import com.xiaotu.repository.CommentRepository;
import com.xiaotu.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 基于API实现Redis缓存
 */
@Service("apiRedisCommentServiceImpl")
public class ApiRedisCommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Comment findById(int comment_id) {
        //先从Redis缓存中查数据
        Object redis = redisTemplate.opsForValue().get("comment_" + comment_id);
        if(redis!=null){
            return (Comment)redis;
        }else {
            //缓存中没有则进入数据库查询
            Optional<Comment> byId = commentRepository.findById(comment_id);
            if (byId.isPresent()){
                Comment comment = byId.get();
                //将查询的结果进行缓存,并设置有效时间一天
                redisTemplate.opsForValue().set("comment_"+comment_id, comment, 1, TimeUnit.DAYS);
                return comment;
            }else {
                return null;
            }
        }
    }
    @Override
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        redisTemplate.opsForValue().set("comment_"+comment.getId(), comment);
        return comment;
    }
    @Override
    public void deleteComment(Integer comment_id) {
        commentRepository.deleteById(comment_id);
        //删除数据后进行缓存删除
        redisTemplate.delete("comment_"+comment_id);
    }

    @Override
    public Comment getComment(Integer comment_id) {
        return null;
    }
}
